document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('mergeForm');
    form.addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为
        const formData = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/merge', true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if(response.success){
                    document.getElementById('status').innerText = 'Merge successful! Download from the link below.';
                    document.getElementById('status').innerHTML += `<a href="${response.downloadLink}">Download Merged PDF</a>`;
                } else {
                    document.getElementById('status').innerText = response.message;
                }
            } else {
                document.getElementById('status').innerText = 'There was a problem with the request.';
            }
        };
        xhr.send(formData);
    });
});

// 新增：动态切换使用说明
function updateInstructions(isMerge) {
    document.getElementById('mergeInstructions').style.display = isMerge ? 'block' : 'none';
    document.getElementById('convertInstructions').style.display = isMerge ? 'none' : 'block';
    document.getElementById('filenameLabel').innerText = isMerge ? '合并后文件名：' : '转换后文件名：';
    document.getElementById('outputFilename').placeholder = isMerge ? 'merged.pdf' : 'converted.docx';
}

// 修改现有的radio监听器
document.querySelectorAll('input[name="operationType"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const isMerge = this.value === 'merge';
        document.getElementById('pdfUploadGroup').style.display = isMerge ? 'block' : 'none';
        document.getElementById('convertUploadGroup').style.display = isMerge ? 'none' : 'block';
        updateInstructions(isMerge);
    });
});

// 初始化时更新说明
updateInstructions(true);

// 修改表单提交逻辑
document.getElementById('mergeForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const operationType = document.querySelector('input[name="operationType"]:checked').value;
    const formData = new FormData();
    
    if (operationType === 'merge') {
        // 合并操作逻辑
        const files = document.getElementById('pdfFiles').files;
        if (files.length < 2) {
            alert('请选择至少两个PDF文件进行合并');
            return;
        }
        Array.from(files).forEach(file => formData.append('pdfFiles', file));
    } else {
        // 转换操作逻辑
        const file = document.getElementById('convertFile').files[0];
        if (!file) {
            alert('请选择要转换的PDF文件');
            return;
        }
        formData.append('pdfFile', file);
    }
    
    formData.append('outputFilename', document.getElementById('outputFilename').value);
    
    try {
        const response = await fetch(operationType === 'merge' ? '/merge' : '/convert', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            const link = `<a href="${result.downloadLink}" class="btn btn-success">下载文件</a>`;
            document.getElementById('status').innerHTML = `操作成功！${link}`;
        } else {
            document.getElementById('status').innerHTML = `操作失败：${result.message}`;
        }
    } catch (error) {
        document.getElementById('status').innerHTML = `请求失败：${error.message}`;
    }
});